package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import shared.pojo.Role
import slick.jdbc.JdbcProfile

import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class MemberDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {


  import utils.MyPostgresProfile.api._

  type MyRow = MemberRow
  val table = Member

  def insert(row: MyRow) = {
    db.run(table += row)
  }

  def selectAll = db.run(table.sortBy(_.id.desc).result.map(_.toList))

  def deleteById(id: Int): Future[Unit] = db.run(table.filter(_.id === id).delete).map(_ => ())

  def selectById(id: Int) = db.run(table.
    filter(_.id === id).result.head)

  def selectByAccountSome(account: String) = db.run(table.
    filter(_.account === account).result.head)

  def selectByAccount(account: String) = db.run(table.
    filter(_.account === account).result.headOption)

  def update(row: MyRow): Future[Unit] = db.run(table.filter(_.account === row.account).update(row)).
    map(_ => ())

  def select(account: String, password: String) = {
    db.run(table.filter(x => x.account === account)
      .filter(_.password === password).result.headOption)
  }

  def selectGetRole(account: String, password: String) = {
    db.run(table.filter(x => x.account === account)
      .filter(_.password === password).result.headOption.map(op => op.map { x => Role.Member }))
  }

  def updates(rows: Seq[MyRow]) = {
    val action = DBIO.sequence {
      rows.map { row =>
        table.filter(_.id === row.id).update(row)
      }
    }.transactionally
    db.run(action)
  }

  def accountExist(account: String) = db.run(table.
    filter(_.account === account).exists.result)

}
